import axios from 'axios'
import obj from '@/common/config.js'
const service = axios.create({
	// withCredentials: true,
	crossDomain: true,
	baseURL: obj.baseUrl,
	timeout: 10000
})
axios.islogin = false
// request拦截器,在请求之前做一些处理
service.interceptors.request.use(
	config => {
		let token = uni.getStorageSync('user_token') || ''
		if (token) {
			config.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带自定义token 请根据实际情况自行修改
		}
		config.headers['Terminal-Type'] = 'app'
		// const methodType = config.method

		config.url = encodeURI(`${config.url}`)

		return config
	}
)

// 配置成功后的拦截器
service.interceptors.response.use(
	res => {
		const response = res.data
		if (response && response.code !== 200) {
			if(response.code=== 401){
				uni.removeStorageSync('user_token')
				uni.navigateTo({
					url: '/subPages/login/index'
				})
			}else{
				uni.showToast({
					title: `${response.msg || ''}`,
					icon: 'none',
					duration: 2000
				})
				
				return Promise.reject(response)
			}

		
		} else {
			return Promise.resolve(response)
		}
	},
	async (error) => {
		if (error.response && error.response.status === 401) {
			

			if (axios.islogin) {
				return false
			}
			axios.islogin = true
			uni.removeStorageSync('user_token')
			// 原先为uni.redirectTo(OBJECT) 被拦截后 无法使用uni.navigateBack()返回上一级
			axios.islogin = false
			// console.log('进入到拦截==')
			uni.navigateTo({
				url: '/subPages/login/index'
			})
		} else {
			uni.showToast({
				title: `${error.message}`,
				icon: 'none',
				duration: 2000
			})
		}
	})

axios.defaults.adapter = function(config) { // 自己定义个适配器，用来适配uniapp的语法
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle')
		var buildURL = require('axios/lib/helpers/buildURL')
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				// console.log('执行完成：', response)
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				}

				settle(resolve, reject, response)
			}
		})
	})
}

// 刷新当前接口数据
function getdata(config) {
	const reqConfig = {
		url: config.url,
		method: config.method
	}

	const newData = config.data ? JSON.parse(config.data) : config.params
	const keyArr = Object.keys(newData)

	if (keyArr.includes('token')) {
		newData.token = uni.getStorageSync('user_token')
	}
	if (config.method === 'post' || config.method === 'POST') {
		reqConfig.data = JSON.stringify(newData)
	} else {
		reqConfig.params = newData
	}
	// console.log(service(reqConfig))
	return service(reqConfig)
}


export default service
